package com.duqc.sentinel.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphO;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.duqc.sentinel.domain.User;
import com.duqc.sentinel.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;

/**
 * @ClassName UserController
 * @Description TODO
 * @Author duqc
 * @Date 2021/5/17
 **/
@Slf4j
@RestController
@RequestMapping("sentinel")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    /**
     * 资源名称
     */
    public static final String RESOURCE_NAME = "userList";
    public static final String RESOURCE_NAME_QUERY_USER_BY_ID = "queryUserById";

    @GetMapping("/list")
    public List<User> getUserList() {
        List<User> userList = null;
        Entry entry = null;
        try {
            //被保护的业务逻辑
            entry = SphU.entry(RESOURCE_NAME);
            userList = this.userService.getList();
        } catch (BlockException e) {
            // 资源访问阻止，被限流或被降级
            return Collections.singletonList(new User(0, "资源访问被限流", "0"));
        } catch (Exception e) {
            // 若需要配置降级规则，需要通过这种方式记录业务异常
            Tracer.traceEntry(e, entry);
        } finally {
            // 务必保证 exit，务必保证每个 entry 与 exit 配对
            if (entry != null) {
                entry.exit();
            }
        }
        return userList;
    }

    @GetMapping("/get/{id}")
    public String queryUserById(@PathVariable("id") String id) {
        if (SphO.entry(RESOURCE_NAME_QUERY_USER_BY_ID)) {
            try {
                return "succcess";
            } finally {
                SphO.exit();
            }
        } else {
            //资源访问阻止，被限流或被降级
            return "Resource is Block!!!";
        }
    }

    @GetMapping("/name")
    public User queryByUserName(String name){
        return this.userService.queryByUserName(name);
    }

    @GetMapping("/add")
    public String add(User user){
        return this.userService.add(user);
    }

}
